// 游戏配置
const config = {
    type: Phaser.AUTO,
    scale: {
        mode: Phaser.Scale.RESIZE,
        parent: 'game-container',
        width: '100%',
        height: '100%',
        min: {
            width: 800,
            height: 600
        }
    },
    backgroundColor: '#1a1a2e',
    scene: [MenuScene, GameScene]
};

// 创建游戏实例
const game = new Phaser.Game(config);

// 菜单场景
function MenuScene() {
    Phaser.Scene.call(this, { key: 'MenuScene' });
}

MenuScene.prototype = Object.create(Phaser.Scene.prototype);

MenuScene.prototype.create = function() {
    const width = this.scale.width;
    const height = this.scale.height;

    // 创建背景图案
    const gridSize = 40;
    for (let x = 0; x < width; x += gridSize) {
        for (let y = 0; y < height; y += gridSize) {
            this.add.rectangle(x, y, 2, 2, 0x16213e, 0.3);
        }
    }

    // 添加标题容器
    const titleContainer = this.add.container(width / 2, height / 3);

    // 添加标题背景
    const titleBg = this.add.rectangle(0, 0, 500, 100, 0x16213e, 0.8);
    titleBg.setStrokeStyle(2, 0x0f3460);

    // 添加标题文本
    const title = this.add.text(0, 0, '贪吃蛇小游戏', {
        fontSize: '64px',
        fill: '#e94560',
        fontFamily: 'Arial Black',
        stroke: '#0f3460',
        strokeThickness: 8
    }).setOrigin(0.5);

    titleContainer.add([titleBg, title]);

    // 创建开始按钮（移除阴影效果）
    const buttonBg = this.add.rectangle(width / 2, height / 2 + 50, 240, 70, 0x16213e);
    buttonBg.setStrokeStyle(2, 0x0f3460);
    
    const startText = this.add.text(width / 2, height / 2 + 50, '开始游戏', {
        fontSize: '32px',
        fill: '#e94560',
        fontFamily: 'Arial',
        fontWeight: 'bold'
    }).setOrigin(0.5);

    // 添加提示文本
    this.add.text(width / 2, height - 100, '按住 S 键可加速', {
        fontSize: '24px',
        fill: '#4ecca3',
        fontFamily: 'Arial'
    }).setOrigin(0.5);

    // 按钮交互
    buttonBg.setInteractive();
    buttonBg.on('pointerover', () => {
        buttonBg.setScale(1.05);
        startText.setScale(1.05);
    });
    buttonBg.on('pointerout', () => {
        buttonBg.setScale(1);
        startText.setScale(1);
    });
    buttonBg.on('pointerdown', () => {
        this.scene.start('GameScene');
    });
};

// 游戏场景
function GameScene() {
    Phaser.Scene.call(this, { key: 'GameScene' });
}

GameScene.prototype = Object.create(Phaser.Scene.prototype);

GameScene.prototype.init = function() {
    this.snake = null;
    this.food = null;
    this.cursors = null;
    this.score = 0;
    this.scoreText = null;
    this.gameOver = false;
    this.direction = 'right';
    this.moveInterval = 250; // 进一步降低移动速度
    this.lastMoveTime = 0;
    this.gridSize = Math.min(this.scale.width, this.scale.height) / 40;
};

GameScene.prototype.create = function() {
    const width = this.scale.width;
    const height = this.scale.height;

    // 创建游戏区域边框
    const gameArea = this.add.rectangle(width/2, height/2, width-40, height-40, 0x16213e, 0.3);
    gameArea.setStrokeStyle(4, 0x0f3460);

    // 初始化蛇的身体
    this.snake = {
        body: [],
        size: this.gridSize,
        color: 0xe94560,
        normalSpeed: 250,
        boostSpeed: 100
    };

    // 创建蛇的初始身体
    const startX = Math.floor(width / 2);
    const startY = Math.floor(height / 2);
    for (let i = 0; i < 3; i++) {
        const segment = this.add.rectangle(
            startX - (i * this.gridSize),
            startY,
            this.snake.size - 2,
            this.snake.size - 2,
            this.snake.color
        ).setStrokeStyle(1, 0x0f3460);
        this.snake.body.push(segment);
    }

    // 创建食物
    this.food = this.add.circle(
        this.gridSize * Math.floor(Phaser.Math.Between(2, (width/this.gridSize) - 2)),
        this.gridSize * Math.floor(Phaser.Math.Between(2, (height/this.gridSize) - 2)),
        this.gridSize/2 - 1,
        0x4ecca3
    ).setStrokeStyle(1, 0x0f3460);

    // 初始化键盘控制
    this.cursors = this.input.keyboard.createCursorKeys();
    this.speedKey = this.input.keyboard.addKey(Phaser.Input.Keyboard.KeyCodes.S);

    // 添加分数显示
    const scoreBg = this.add.rectangle(100, 50, 160, 50, 0x16213e, 0.8);
    scoreBg.setStrokeStyle(2, 0x0f3460);
    
    this.scoreText = this.add.text(100, 50, '分数: 0', {
        fontSize: '28px',
        fill: '#4ecca3',
        fontFamily: 'Arial',
        fontWeight: 'bold'
    }).setOrigin(0.5);
};

GameScene.prototype.update = function(time) {
    if (this.gameOver) {
        return;
    }

    // 检查加速键
    this.moveInterval = this.speedKey.isDown ? this.snake.boostSpeed : this.snake.normalSpeed;

    // 控制移动方向
    if (this.cursors.left.isDown && this.direction !== 'right') {
        this.direction = 'left';
    }
    else if (this.cursors.right.isDown && this.direction !== 'left') {
        this.direction = 'right';
    }
    else if (this.cursors.up.isDown && this.direction !== 'down') {
        this.direction = 'up';
    }
    else if (this.cursors.down.isDown && this.direction !== 'up') {
        this.direction = 'down';
    }

    if (time >= this.lastMoveTime + this.moveInterval) {
        this.lastMoveTime = time;
        this.moveSnake();
    }

    if (time >= this.lastMoveTime + this.moveInterval) {
        this.lastMoveTime = time;
        this.moveSnake();
    }
};

GameScene.prototype.moveSnake = function() {
    let x = this.snake.body[0].x;
    let y = this.snake.body[0].y;

    switch (this.direction) {
        case 'left': x -= this.gridSize; break;
        case 'right': x += this.gridSize; break;
        case 'up': y -= this.gridSize; break;
        case 'down': y += this.gridSize; break;
    }

    if (Math.abs(x - this.food.x) < this.gridSize/2 && Math.abs(y - this.food.y) < this.gridSize/2) {
        this.score += 10;
        this.scoreText.setText('分数: ' + this.score);

        this.food.x = this.gridSize * Math.floor(Phaser.Math.Between(2, (this.scale.width/this.gridSize) - 2));
        this.food.y = this.gridSize * Math.floor(Phaser.Math.Between(2, (this.scale.height/this.gridSize) - 2));

        const newSegment = this.add.rectangle(
            this.snake.body[this.snake.body.length - 1].x,
            this.snake.body[this.snake.body.length - 1].y,
            this.snake.size - 2,
            this.snake.size - 2,
            this.snake.color
        ).setStrokeStyle(1, 0x0f3460);
        this.snake.body.push(newSegment);
    } else {
        for (let i = this.snake.body.length - 1; i > 0; i--) {
            this.snake.body[i].x = this.snake.body[i - 1].x;
            this.snake.body[i].y = this.snake.body[i - 1].y;
        }
    }

    this.snake.body[0].x = x;
    this.snake.body[0].y = y;

    if (this.checkCollision(x, y)) {
        this.handleGameOver();
    }
};

GameScene.prototype.checkCollision = function(x, y) {
    if (x < 20 || x > this.scale.width - 20 || y < 20 || y > this.scale.height - 20) {
        return true;
    }

    for (let i = 1; i < this.snake.body.length; i++) {
        if (Math.abs(x - this.snake.body[i].x) < this.gridSize/2 && 
            Math.abs(y - this.snake.body[i].y) < this.gridSize/2) {
            return true;
        }
    }

    return false;
};

GameScene.prototype.handleGameOver = function() {
    this.gameOver = true;

    // 创建模糊背景
    const overlay = this.add.rectangle(
        this.scale.width/2,
        this.scale.height/2,
        this.scale.width,
        this.scale.height,
        0x000000,
        0.7
    );

    // 创建结果面板
    const panel = this.add.rectangle(
        this.scale.width/2,
        this.scale.height/2,
        400,
        300,
        0x16213e,
        0.95
    ).setStrokeStyle(4, 0x0f3460);

    // 添加游戏结束文本
    this.add.text(this.scale.width/2, this.scale.height/2 - 80, '游戏结束!', {
        fontSize: '48px',
        fill: '#e94560',
        fontFamily: 'Arial Black',
        stroke: '#0f3460',
        strokeThickness: 6
    }).setOrigin(0.5);

    // 添加分数显示
    this.add.text(this.scale.width/2, this.scale.height/2, '最终分数: ' + this.score, {
        fontSize: '32px',
        fill: '#4ecca3',
        fontFamily: 'Arial',
        fontWeight: 'bold'
    }).setOrigin(0.5);

    // 创建重新开始按钮（移除阴影效果）
    const buttonBg = this.add.rectangle(
        this.scale.width/2, 
        this.scale.height/2 + 80, 
        200, 
        60, 
        0x16213e
    ).setStrokeStyle(2, 0x0f3460);

    const restartText = this.add.text(this.scale.width/2, this.scale.height/2 + 80, '再来一局', {
        fontSize: '28px',
        fill: '#e94560',
        fontFamily: 'Arial',
        fontWeight: 'bold'
    }).setOrigin(0.5);

    // 按钮交互
    buttonBg.setInteractive();
    buttonBg.on('pointerover', () => {
        buttonBg.setScale(1.05);
        restartText.setScale(1.05);
    });
    buttonBg.on('pointerout', () => {
        buttonBg.setScale(1);
        restartText.setScale(1);
    });
    buttonBg.on('pointerdown', () => {
        this.scene.restart();
    });
};